<style lang="stylus" scoped>
  .z_index_10
    z-index 10
  .login_con
    width 350px
    background-color rgba(256,256,256,.9)
    right 80px
    top 80px
</style>

<template>
  <div @keyup.enter="loginIn">
    <transition-group
      appear
      enter-active-class="animated slideInRight"
      leave-active-class="animated slideInLeft">
      <q-card v-if="isWhere === 'login'" key="login" class="fixed z_index_10 login_con q-pa-sm">
        <q-card-section class="q-pa-sm row justify-center">
          <q-img style="width:70%" src="statics/app_nav_logo.png"/>
        </q-card-section>
        <q-card-section class="q-pa-sm">
          <q-input
            ref="tenant"
            v-model="loginForm.tenantId"
            :rules="[ val => !!val || $t('租户名不能为空') ]"
            lazy-rules
            :label="$t('租户')">
            <template v-slot:prepend>
              <q-icon name="group" class="text-primary"/>
            </template>
            <template v-slot:append v-if="!!loginForm.tenantId">
              <q-icon name="close" @click="loginForm.tenantId = ''" class="cursor-pointer" />
            </template>
          </q-input>
          <q-input
            ref="username"
            v-model="loginForm.username"
            :error="$v.loginForm.username.$error"
            @blur="$v.loginForm.username.$touch"
            bottom-slots
            :label="$t('用户')">
            <template v-slot:prepend>
              <q-icon name="person" class="text-primary"/>
            </template>
            <template v-slot:error>
              {{ $t('用户名不能为空') }}
            </template>
            <template v-slot:append v-if="!!loginForm.username">
              <q-icon name="close" @click="loginForm.username = ''" class="cursor-pointer" />
            </template>
          </q-input>
          <q-input
            ref="password"
            v-model="loginForm.password"
            :label="$t('密码')"
            :error="$v.loginForm.password.$error"
            @blur="$v.loginForm.password.$touch"
            bottom-slots
            :type="isPwd ? 'password' : 'text'">
            <template v-slot:prepend>
              <q-icon name="lock" class="text-primary"/>
            </template>
            <template v-slot:error>
              {{ $v.loginForm.password.required ? $t('密码不能少于6个字符'): $t('密码不能为空') }}
            </template>
            <template v-slot:append>
              <q-icon
                :name="isPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="isPwd = !isPwd"
              />
            </template>
          </q-input>
          <q-input
            ref="weixinCode"
            v-model="loginForm.weixinCode"
            :error="$v.loginForm.weixinCode.$error"
            @blur="$v.loginForm.weixinCode.$touch"
            bottom-slots
            label="验证码">
            <template v-slot:prepend>
              <q-icon name="report_problem" class="text-primary"/>
            </template>
            <template v-slot:error>
              验证码不能为空！
            </template>
            <template v-slot:append v-if="!!loginForm.weixinCode">
              <q-icon name="close" @click="loginForm.weixinCode = ''" class="cursor-pointer" />
            </template>
          </q-input>
          <q-checkbox left-label v-model="rmbme" val="1" label="记住密码" />
        </q-card-section>
        <q-card-actions class="q-mb-md">
          <q-btn type="submit" class="full-width" color="primary" :loading="loadingLogin" @click="loginIn">{{ $t('登 录')}}</q-btn>
          <!-- <q-btn class="full-width q-mt-md" color="secondary" @click="toRegister">{{ $t('注 册')}}</q-btn> -->
        </q-card-actions>
      </q-card>
    </transition-group>
  </div>
</template>

<script>
import { required, minLength } from 'vuelidate/lib/validators'
// import { SessionStorage } from 'quasar'
export default {
  data () {
    return {
      isPwd: true,
      loadingLogin: false,
      isWhere: 'login',
      // login
      loginForm: {
        tenantId: 'qeweb',
        username: 'admin',
        password: '111111',
        weixinCode: ''
      },
      scoket: '',
      reconnectData: null,
      lockReconnect: false,
      timeout: 10000, // 10s一次心跳检测
      timeoutObj: null,
      serverTimeoutObj: null,
      rmbme: []
    }
  },
  validations: {
    loginForm: {
      username: { required },
      password: { required, minLength: minLength(6) },
      weixinCode: { required }
    }
  },
  watch: {
    rmbme (rmbme) {
      console.log(rmbme)
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      // if (typeof (WebSocket) === 'underfined') {
      //   alert('你的浏览器不支持webSocket')
      // } else {
      //   console.log(this.scoket)
      // }
    },
    websocketonerror () {
      console.log('连接失败')
      this.reconnect()
    },
    reconnect () {
      if (this.lockReconnect) {
        // 这里很关键，因为连接失败之后之后会相继触发 连接关闭，不然会连接上两个 WebSocket
        return
      }
      this.lockReconnect = true
      this.reconnectData && clearTimeout(this.reconnectData)
      this.reconnectData = setTimeout(() => {
        this.loginIn()
        this.lockReconnect = false
      }, 5000)
    },
    loginIn () {
      this.$v.loginForm.$touch()
      if (!this.$v.loginForm.$error) {
        // const url = 'ws://118.178.94.163:9080/login/signin'
        // this.scoket = new WebSocket(url)
        // this.scoket.onerror = this.websocketonerror
        // console.log(this.scoket)
        this.loadingLogin = true
        // const { tenantId, username, password } = this.loginForm
        this.$api({
          method: 'post',
          url: '/login/signin',
          params: this.loginForm,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
            this.$store.commit('user/userName', this.loginForm.username)
            this.$q.sessionStorage.set('userName', this.loginForm.username)
            this.$store.commit('user/loginIn', data)
            this.$router.push({ path: '/index' })
            let datas = data.userDTO.views
            let cols = data.userDTO.cols // 字段
            let operates = data.userDTO.operates
            let tabs = data.userDTO.tabs
            let has = []
            if (datas.length !== 0) {
              this.$q.sessionStorage.set('men', JSON.stringify(datas))
            }
            if (cols.length !== 0) {
              cols.forEach(item => {
                has.push(item)
              })
            }
            if (operates.length !== 0) {
              operates.forEach(item => {
                has.push(item)
              })
            }
            if (tabs.length !== 0) {
              tabs.forEach(item => {
                has.push(item)
              })
            }
            if (has.length !== 0) {
              this.$q.sessionStorage.set('col', JSON.stringify(has))
            }
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingLogin = false
        // if (tenantId === 'qeweb' && username === 'admin' && password === '111111') {
        //   this.$store.commit('user/loginIn', { tokenType: 'qeweb', accessToken: 'token1000' })
        //   this.$router.push({ path: '/index' })
        // } else {
        //   this.$q.notify({
        //     message: '账号密码有误请检查',
        //     color: 'negative',
        //     icon: 'error_outline',
        //     position: 'top-right',
        //     timeout: 3000
        //   })
        // }
      }
    },
    toRegister () {
      this.$router.push({ path: '/account/register' })
    }
  }
}
</script>
